#include "cppn.hh"
#include "evolution/genome.hh"
#include <fstream>
#include <iostream>
#include <iomanip>

#include "constants.hh"
#include "visualize.hh"
#include "evolution/individual.hh"

using namespace std;
using namespace cppn;


int main (int argc, char** argv) {
    shared_ptr<evolution::Genome> genome;

    if (argc == 2) {
        ifstream fin{argv[1]};
        
        genome = make_shared<evolution::Genome>(TOTAL_INPUT_NODES);
        fin >> *genome;

    } else {
        genome = evolution::Genome::empty_genome(INITIAL_TOTAL_NODES, TOTAL_INPUT_NODES);
    }

   
    bool exit = false;
    while (!exit) {

        CPPN cppn{genome};
    
        HypercubeWindow visualizer { 200, 200, &cppn };
        visualizer.show();
        visualizer.render();

        bool quit = false;
        SDL_Event e;
        while (!quit) {
            
            while (SDL_PollEvent(&e)) {
                if (e.type == SDL_QUIT
                 || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_q)) { exit = true; quit = true; }

                else if (e.type == SDL_KEYDOWN) {
                    bool change = false;

                    if (e.key.keysym.sym == SDLK_UP) change = visualizer.scroll(0, 0.05f);
                    else if (e.key.keysym.sym == SDLK_DOWN) change = visualizer.scroll(0, -0.05f);
                    else if (e.key.keysym.sym == SDLK_LEFT) change = visualizer.scroll(-0.05f, 0);
                    else if (e.key.keysym.sym == SDLK_RIGHT) change = visualizer.scroll(0.05f, 0);
                    else if (e.key.keysym.sym == SDLK_SPACE) quit = true;
                    else if (e.key.keysym.sym == SDLK_s) {
                        ofstream fout("saved");
                        fout << *genome << endl;
                        cout << "Genome was saved.\n";
                    }
                    
                    if (change) visualizer.render();
                }
            }
            visualizer.wait(10);
        }
        if (!exit) genome->mutate();
    }
}









